/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package AFEED;

/**
 *
 * @author comiang
 */
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class RSSReader1 {

private static RSSReader1 instance = null;

private RSSReader1() {
}

public static RSSReader1 getInstance() {
if(instance == null) {
instance = new RSSReader1();
}
return instance;
}


public void writeNews(String text) {
try {

DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
URL u = new URL("http://pratyush.in/feed/rss"); // your feed url
 InputStream is = null ;
try {
             is = new ByteArrayInputStream(text.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

Document doc = builder.parse(is);

NodeList nodes = doc.getElementsByTagName("item");

for(int i=0;i<nodes.getLength();i++) {

Element element = (Element)nodes.item(i);
System.out.println("Title: " + getElementValue(element,"title"));
//System.out.println("Link: " + getElementValue(element,"link"));
System.out.println("Publish Date: " + getElementValue(element,"pubDate"));
System.out.println("author: " + getElementValue(element,"dc:creator"));
//System.out.println("comments: " + getElementValue(element,"wfw:comment"));
//System.out.println("description: " + getElementValue(element,"description"));
System.out.println();
}//for
}//try
catch(Exception ex) {
ex.printStackTrace();
}

}

private String getCharacterDataFromElement(Element e) {
try {
Node child = e.getFirstChild();
if(child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
}
catch(Exception ex) {

}
return "";
} //private String getCharacterDataFromElement

protected float getFloat(String value) {
if(value != null && !value.equals("")) {
return Float.parseFloat(value);
}
return 0;
}

protected String getElementValue(Element parent,String label) {
return getCharacterDataFromElement((Element)parent.getElementsByTagName(label).item(0));
}

//public static void main(String[] args) {
//RSSReader reader = RSSReader.getInstance();
//reader.writeNews();
//}
}

